/********************************************************************
	created:	2010/07/27
	created:	27:7:2010   17:27
	filename: 	D:\Proj\gcstock\code\C++\Base\GCThread.h
	file path:	D:\Proj\gcstock\code\C++\Base
	file base:	GCThread
	file ext:	h
	author:		Greg Song
	
	purpose:	Thread operations   
*********************************************************************/


#ifndef _GC_THREAD_H_
#define _GC_THREAD_H_
#include "GCHeader.h"
#include <iostream>
#include <string>
#include "pthread.h"
#include "semaphore.h"
#include "GCArray.h"

namespace gcstock
{
    class GC_Mutex
    {
    public:
        enum TYPE{MUTEX_NORMAL = PTHREAD_MUTEX_NORMAL,
            MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK,
            MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE,
            MUTEX_DEFAULT = PTHREAD_MUTEX_DEFAULT};
        GC_Mutex(){pthread_mutex_init (&_mutex,NULL);};
        GC_Mutex(TYPE t);
        ~GC_Mutex();
        
        // Lock & unlock
        void lock();
        
        void unlock();
        // Time lock
        
    protected:
        
    private:
        pthread_mutex_t _mutex;
    };

    // This guard may cause dead lock
    class GC_Guard
    {
    public:
        GC_Guard(pthread_mutex_t& m):mutex(m){
            pthread_mutex_lock (&mutex);
        };
        
        ~GC_Guard(){
            pthread_mutex_unlock(&mutex);
        }
    private:
        pthread_mutex_t& mutex;
    };

    class GC_GuardEX
    {
    public:
        GC_GuardEX(GC_Mutex& m,int s = 0):_mutex(m){
            if(s == 0)
            {
                _mutex.lock();
            }
            else
            {
                // Timed lock
            }
            
        }
        
        ~GC_GuardEX(){
            _mutex.unlock();
        }
        
    private:
        GC_Mutex _mutex;
        int status;
    };


    class GC_Cond
    {
    public:
        GC_Cond(pthread_mutex_t& m,pthread_cond_t& c):mutex(m),cond(c){}
        ~GC_Cond(){}
        void setCond(){}
        void wait();
        void signal();
    private:
        GC_Cond& operator=(const GC_Cond&){};
        // condition;
        pthread_mutex_t& mutex;
        pthread_cond_t& cond;
    };

    class GC_Thread_Key
    {
    public:
        
    protected:
        
    private:
        
    };

    class GC_Task_Base
    {
    public:    
        void active(int num);
        
        virtual int svc() = 0;
        
        virtual ~GC_Task_Base(){};
        
        virtual void cancel();
        
        static void* svc_run(void*);
    protected:
        
    private:
        GCVArray<pthread_t*> pidList;
    };
}

#endif // _GC_THREAD_H_